package com.todod.controller;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.todod.annotaion.NotLogging;
import com.todod.common.util.CheckData;
import com.todod.common.util.EncryptUtil;
import com.todod.common.util.JwtUtil;
import com.todod.common.util.SnowflakeIdGenerator;
import com.todod.dto.UserDto;
import com.todod.entity.QueryEntry;
import com.todod.entity.ResUser;
import com.todod.entity.ResultData;
import com.todod.model.Department;
import com.todod.model.Menu;
import com.todod.model.RoleAuthority;
import com.todod.model.RoleMenu;
import com.todod.model.User;
import com.todod.service.IDepartmentService;
import com.todod.service.ILoginLogService;
import com.todod.service.IMenuService;
import com.todod.service.IRoleAuthorityService;
import com.todod.service.IRoleMenuService;
import com.todod.service.IUserService;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gsh
 * @since 2020-10-14
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseManageController {
	@Autowired
	private IUserService iUserService;
	@Autowired
	private ILoginLogService iLoginLogService;
	@Autowired
	private IRoleAuthorityService iRoleAuthorityService;
	@Autowired
	private IMenuService iMenuService;
	@Autowired
	private IRoleMenuService iRoleMenuService;
	@Autowired
	private IDepartmentService departmentservice;

	@PostMapping("/login")
	@NotLogging
	public ResultData login(@RequestBody UserDto user, HttpServletRequest res, HttpServletResponse rep) {
		if (StringUtils.isBlank(user.getUserName())) {
			return ResultData.error(ResultData.ESTIMATE_ERROR_CODE, "请输入用户名");
		}
		if (StringUtils.isBlank(user.getPassword())) {
			return ResultData.error(ResultData.ESTIMATE_ERROR_CODE, "请输入密码");
		}

		User u = iUserService.login(user.getUserName(), user.getPassword());

		// 记录日志
		iLoginLogService.add(u, res, user.getUserName(), "1");

		if (u == null) {
			return ResultData.error(ResultData.USER_LOGIN_AcountError, "用户名或密码错误");
		}
		if (!"1".equals(u.getState())) {
			return ResultData.error(ResultData.USER_LOGIN_StateError, "用户名或密码错误");
		}

//		String token = EncryptUtil.encrypt(u.getId() + "");
		String token = JwtUtil.getToken(u.getId() + "");
		HashMap<String, String> hashMap = new HashMap<>();
		hashMap.put("token", token);

		return ResultData.success("ok", hashMap);
	}

	@RequestMapping("/info")
	public ResultData info(@RequestAttribute Long _userId) {
		User user = iUserService.getById(_userId);

		List<RoleAuthority> listByRoleId = iRoleAuthorityService.getRoleAuthority(user.getRoleId());
		List<String> arrayList = listByRoleId.stream().map(x -> x.getAuthorityCode()).collect(Collectors.toList());

		Department department = departmentservice.getById(user.getDepartid());

		HashMap<String, Object> hashMap = new HashMap<>();

		arrayList.add("");
		hashMap.put("roles", arrayList);
		hashMap.put("introduction", "");
		hashMap.put("avatar", "");
		hashMap.put("name", user.getNickName());
		hashMap.put("dName", department.getName());
		hashMap.put("dId", department.getId());
		return ResultData.success("ok", hashMap);
	}

	/**
	 * 获取用户菜单
	 * 
	 * @Title: getMenu
	 * @Description:
	 * @author gsh
	 * @date 2020年11月24日
	 * @param _userId
	 * @return
	 */
	@RequestMapping("/getMenu")
	public ResultData getMenu(@RequestAttribute Long _userId) {
		User user = iUserService.getById(_userId);
		List<RoleMenu> roleMenuList = iRoleMenuService.getByRoleId(user.getRoleId());
		List<Menu> menuList = iMenuService.getList();

		List<Menu> rmenuList = new ArrayList<Menu>();
		for (Menu menu : menuList) {
			for (RoleMenu roleMenu : roleMenuList) {
				if (roleMenu.getMenuId().equals(menu.getId())) {
					if (!rmenuList.contains(menu)) {
						rmenuList.add(menu);
					}
					// 获取父节菜单
					getParamMenu(rmenuList, menuList, menu);
				}
			}
		}

		List<Menu> list = rmenuList.stream().sorted(Comparator.comparing(Menu::getSortNum))
				.collect(Collectors.toList()); // 排序
		return ResultData.success("ok", list);
	}

	private void getParamMenu(List<Menu> rmenuList, List<Menu> menuList, Menu menu) {
		Optional<Menu> optional = menuList.stream().filter(x -> x.getId().equals(menu.getParentId())).findAny();
		if (optional.isPresent()) {
			Menu menu2 = optional.get();
			if (!rmenuList.contains(menu2)) {
				rmenuList.add(menu2);
			}
			getParamMenu(rmenuList, menuList, menu2);
		}

	}

	@PostMapping("/logout")
	@NotLogging
	public ResultData logout() {

		return ResultData.success("ok");
	}

	@RequestMapping("/getList")
	public ResultData getList(@RequestBody QueryEntry queryEntry, @RequestAttribute Long _userId) {
		List<Long> list = new ArrayList<>();
		if (queryEntry.getId() != null) {
			list = departmentservice.getdepatrtid2(queryEntry.getId());
		} else {
			list = departmentservice.getdepatrtid(iUserService.getById(_userId));
		}

		queryEntry.setDepertid(list);
		IPage<UserDto> page = iUserService.getList(queryEntry);
		return ResultData.success("ok", page);
	}

	@RequestMapping("/getDnameList")
	public ResultData getDnameList(@RequestBody QueryEntry queryEntry, @RequestAttribute Long _userId) {
		List<Long> list = new ArrayList<>();
		if (queryEntry.getId() != null) {
			list = departmentservice.getdepatrtid2(queryEntry.getId());
		} else {
			list = departmentservice.getdepatrtid(iUserService.getById(_userId));
		}

		queryEntry.setDepertid(list);
		IPage<UserDto> page = iUserService.getList(queryEntry);
		return ResultData.success("ok", page);
	}

	/**
	 * 管理端添加用户
	 * 
	 * @param _userId
	 * @param user
	 * @return
	 */
	@PostMapping("/save")
	public ResultData save(@RequestAttribute Long _userId, @RequestBody ResUser user) {
		iUserService.saveData(_userId, user);
		return ResultData.success("ok");
	}

	/**
	 * 修改禁用状态
	 * 
	 * @param _userId
	 * @param userId
	 * @return
	 */
	@PostMapping("/disable")
	public ResultData disable(@RequestAttribute Long _userId, Long userId) {
		iUserService.updateState(_userId, userId, "2");

		return ResultData.success("ok");
	}

	@PostMapping("/enable")
	public ResultData enable(@RequestAttribute Long _userId, Long userId) {
		iUserService.updateState(_userId, userId, "1");

		return ResultData.success("ok");
	}

	@PostMapping("/repStallsPasssWord")
	public ResultData editaStallsPasssWord(@RequestAttribute Long _userId, Long userId) {
		// 重置密码
		iUserService.editPasssWord(_userId, userId, "Aa123456");

		return ResultData.success("ok");
	}

	@GetMapping("/getAllUser")
	public ResultData getAllUser() {
		List<User> list = iUserService.getAllUser();

		return ResultData.success("ok", list);
	}

	/**
	 * 修改密码
	 * 
	 * @Title: updatepassword
	 * @Description:
	 * @author gsh
	 * @date 2019年10月21日
	 * @param _userId
	 * @return
	 */
	@PostMapping("/editPasssWord")
	public ResultData editPasssWord(@RequestAttribute Long _userId, String newPassWord, String oldPassWird) {

		User user = iUserService.getById(_userId);
		if (user == null) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "用户不存在");
		}

		// 校验密码
		if (!user.getPassword().equals(EncryptUtil.encrypt(oldPassWird))) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "原密码错误");
		}

		if (CheckData.checkPassword2(newPassWord)) {
			return ResultData.error(ResultData.ESTIMATE_ERROR_CODE, "密码必须包含大小写字母和数字，并且不得少于6位字符，大于15位字符");
		}
		if (newPassWord.equals(oldPassWird)) {
			return ResultData.error(ResultData.ESTIMATE_ERROR_CODE, "新密码不能与原密码相同");
		}

		// 修改密码
		iUserService.editPasssWord(_userId, _userId, newPassWord);

		return ResultData.success("ok");
	}

	@GetMapping("/getId")
	public ResultData getId() {
		return ResultData.success("ok", SnowflakeIdGenerator.getId());
	}

}
